<template>
  <el-card class="login-card">
    <h2>登录</h2>
    <el-form :model="form" status-icon>
      <el-form-item prop="email" label="邮箱" :rules="[{ required: true, message: '邮箱不能为空', trigger: 'blur' }]">
        <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码" :rules="[{ required: true, message: '密码不能为空', trigger: 'blur' }]">
        <el-input type="password" v-model="form.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="form.rememberMe">记住我</el-checkbox>
      </el-form-item>

      <el-button type="primary" @click="submit">登录</el-button>

    </el-form>
  </el-card>
</template>

<script>


import httpService from "@/services/httpService";

export default {
  data() {
    return {
      form: {
        email: '',
        password: '',
        rememberMe: false
      }
    };
  },

  mounted() {
    // 页面加载时，从 LocalStorage 获取已存储的用户名和记住我状态
    const storedUsername = localStorage.getItem('username');
    const rememberMe = localStorage.getItem('rememberMe') === 'true';

    if (rememberMe && storedUsername) {
      this.form.username = storedUsername;
      this.form.rememberMe = true;
    }
  },
  methods: {
    async submit() {
      try {
        // 调用登录 API
        console.log(this.form);

        // 验证输入
        if (!this.validateEmail(this.form.email)) {
          throw new Error('无效的邮箱格式');
        }
        if (!this.validatePassword(this.form.password)) {
          throw new Error('密码必须至少8个字符长');
        }

        // 发送登录请求
        const response = await httpService.post('/api/v1/auth/login', {
          email: this.form.email,
          password: this.form.password,
        });
        // 登录成功后，将用户信息存储在 LocalStorage 或 Cookies 中
        if (this.form.rememberMe) {
          localStorage.setItem('token', response.data.token); // 存储 token
          localStorage.setItem('username', this.form.username); // 存储用户名
          localStorage.setItem('rememberMe', true); // 存储“记住我”状态
        } else {
          localStorage.removeItem('token'); // 不记住时清除
          localStorage.removeItem('username');
          localStorage.removeItem('rememberMe');
        }

        // 保存 token
        const { token } = response;
        httpService.setToken(token);

        console.log('登录成功:', response);
        // 可以在这里处理登录成功后的逻辑，例如跳转到首页
        this.$router.push('/dashboard');
      } catch (error) {
        console.error('登录失败:', error);
        // 可以在这里处理登录失败的逻辑，例如显示错误提示
        this.$message.error(error.message);
      }
    },
    validateEmail(email) {
      const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return re.test(email);
    },
    validatePassword(password) {
      return password.length >= 4; // 至少8个字符
    }
  }
}
</script>

<style scoped>
.login-card {
  width: 300px;
  margin: 100px auto;
}
</style>
